<template>
  <div class="warehouse-update-page">
    <el-card class="section-card">
      <div class="section-title">基础信息</div>
      <el-form ref="ruleFormRef" :model="ruleForm" label-width="100px" class="base-form">
        <el-container>
          <el-aside width="600px">
            <el-form-item label="仓库编号">
              <el-input v-model="ruleForm.warehouseCode" placeholder="自动获取系统编号" readonly />
            </el-form-item>
            <el-form-item label="仓库容量/m³">
              <el-input v-model="ruleForm.warehouseCapacity" />
            </el-form-item>
            <el-form-item label="仓库主管">
              <el-select v-model="ruleForm.userId" placeholder="请选择" filterable>
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="仓库地址">
              <el-input v-model="ruleForm.warehouseAddress" />
            </el-form-item>
            <el-form-item label="排序">
              <el-input v-model="ruleForm.warehouseSort" />
            </el-form-item>
            <el-form-item v-if="ruleForm.warehouseState !== '2'" label="锁定">
              <el-switch v-model="ruleForm.warehouseLock" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" v-model="ruleForm.warehouseNote" />
            </el-form-item>
          </el-aside>
          <el-aside width="600px">
            <el-form-item label="仓库名称">
              <el-input v-model="ruleForm.warehouseName" />
            </el-form-item>
            <el-form-item label="库管部门">
              <el-input
                v-model="selectedOrganizationName"
                placeholder="请选择库管部门"
                readonly
                @click="openOrganizationDialog"
              >
                <template #append>
                  <el-button icon="Search" @click="openOrganizationDialog">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="ruleForm.warehousePhone" />
            </el-form-item>
            <el-form-item label="仓库状态">
              <el-radio-group v-model="ruleForm.warehouseState">
                <el-radio label="1">启用</el-radio>
                <el-radio label="2">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-aside>
        </el-container>
      </el-form>
    </el-card>

    <el-card class="section-card">
      <div class="section-title">仓库明细</div>
      <div class="table-toolbar">
        <el-button type="success" @click="openAddDrawer">新增</el-button>
        <el-button type="primary" @click="openImportDrawer">导入库位</el-button>
      </div>
      <el-table :data="tableDatastoragelocation" border style="width: 100%">
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="storagelocationCode" label="库位编号" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.storagelocationCode" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationName" label="库位名称" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.storagelocationName" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationCapacity" label="库位容量" width="140">
          <template #default="scope">
            <el-input v-model="scope.row.storagelocationCapacity" size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationSort" label="排序" width="120">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.storagelocationSort"
              size="small"
              :min="0"
              :controls="false"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="库位主管" width="150">
          <template #default="scope">
            <el-select v-model="scope.row.userId" size="small" placeholder="请选择" style="width: 100%" filterable>
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationState" label="库位状态" width="130">
          <template #default="scope">
            <el-select v-model="scope.row.storagelocationState" size="small" style="width: 100%">
              <el-option label="启用" :value="1" />
              <el-option label="停用" :value="2" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="storagelocationNote" label="备注">
          <template #default="scope">
            <el-input v-model="scope.row.storagelocationNote" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="saveStoragelocation(scope.row)"
              :loading="scope.row.saving"
            >
              保存
            </el-button>
            <el-button link type="danger" size="small" @click="deleteStoragelocation(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container" v-if="tableDatastoragelocation.length">
        <div class="pagination-info">共{{ tableDatastoragelocation.length }}条</div>
      </div>
    </el-card>

    <div class="footer-card">
      <el-button @click="router.back()">关闭</el-button>
      <el-button type="primary" @click="saveWarehouse" :loading="saving">保存</el-button>
    </div>

    <el-dialog v-model="organizationDialogVisible" title="选择库管部门" width="500px">
      <el-input
        v-model="organizationSearchText"
        placeholder="请输入部门名称或编号"
        clearable
        style="margin-bottom: 10px"
      />
      <el-tree
        ref="treeRef"
        :data="organizationTree"
        :props="organizationTreeProps"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="handleOrganizationSelect"
        style="max-height: 400px; overflow: auto;"
      />
      <template #footer>
        <el-button @click="organizationDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="addDrawerVisible" title="新增库位" direction="rtl" size="620px">
      <div class="drawer-content">
        <el-form label-width="110px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库位编号">
                <el-input v-model="addStoragelocation.storagelocationCode" readonly placeholder="自动获取系统编号">
                  <template #append>
                    <el-button @click="generateStoragelocationCode" :loading="generatingLocationCode">自动生成</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="库位名称">
                <el-input v-model="addStoragelocation.storagelocationName" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库位容量/m³">
                <el-input v-model="addStoragelocation.storagelocationCapacity" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序">
                <el-input-number v-model="addStoragelocation.storagelocationSort" :min="0" :controls="false" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="库位状态">
                <el-radio-group v-model="addStoragelocation.storagelocationState">
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="2">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库主管">
                <el-input
                  v-model="selectedAddUserName"
                  placeholder="请选择"
                  readonly
                  @click="openUserDialog"
                >
                  <template #append>
                    <el-button icon="Search" @click="openUserDialog">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注">
            <el-input v-model="addStoragelocation.storagelocationNote" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="addDrawerVisible = false">取消</el-button>
        <el-button type="primary" @click="createStoragelocation" :loading="addingStorage">保存</el-button>
      </template>
    </el-drawer>

    <el-dialog v-model="userDialogVisible" title="请选择库位主管" width="360px">
      <el-input
        v-model="userSearchText"
        placeholder="请输入姓名搜索"
        clearable
        style="margin-bottom: 12px"
      />
      <div class="user-list-dialog">
        <div
          v-for="user in filteredUsers"
          :key="user.userId"
          class="user-item"
          @click="selectUser(user)"
        >
          <div class="user-name">{{ user.userName }}</div>
          <div class="user-account">{{ user.userAccount }}</div>
        </div>
        <div v-if="filteredUsers.length === 0" class="empty-tip">暂无数据</div>
      </div>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch, toRaw } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
import myaxios from '@/http/MyAxios'

const router = useRouter()
const route = useRoute()
const warehouseId = ref<number | null>(null)
const ruleFormRef = ref<FormInstance>()
const saving = ref(false)

const ruleForm = reactive({
  warehouseCode: '',
  warehouseName: '',
  warehouseCapacity: '',
  userId: '',
  storagelocationNum: 0,
  warehouseAddress: '',
  warehouseSort: '',
  warehouseLock: false,
  warehouseNote: '',
  organizationId: '',
  warehousePhone: '',
  accountName: '',
  warehouseState: '1'
})

const selectedOrganizationName = ref('')
const organizationDialogVisible = ref(false)
const organizationTree = ref<any[]>([])
const organizationTreeProps = {
  children: 'children',
  label: 'organizationName'
}
const organizationSearchText = ref('')
const treeRef = ref<TreeInstance>()

const userOptions = ref<any[]>([])
const tableDatastoragelocation = ref<any[]>([])

const addDrawerVisible = ref(false)
const generatingLocationCode = ref(false)
const addingStorage = ref(false)
const addStoragelocation = reactive({
  storagelocationName: '',
  storagelocationCode: '',
  storagelocationCapacity: '',
  userId: '',
  storagelocationSort: 0,
  storagelocationState: 1,
  storagelocationNote: ''
})
const selectedAddUserName = ref('')
const userDialogVisible = ref(false)
const userSearchText = ref('')
const filteredUsers = ref<any[]>([])

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  const segments = (rule?.timeRule || '')
    .split(',')
    .map((s: string) => s.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const indexA = TIME_SEGMENT_ORDER.indexOf(a)
      const indexB = TIME_SEGMENT_ORDER.indexOf(b)
      if (indexA === -1 && indexB === -1) return 0
      if (indexA === -1) return 1
      if (indexB === -1) return -1
      return indexA - indexB
    })

  const datePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY': return String(now.getFullYear())
        case 'YY': return String(now.getFullYear()).slice(-2)
        case 'MM': return pad(now.getMonth() + 1)
        case 'DD': return pad(now.getDate())
        case 'HH': return pad(now.getHours())
        case 'MI': return pad(now.getMinutes())
        case 'SS': return pad(now.getSeconds())
        default: return ''
      }
    })
    .join('')
  const seq = '1'.padStart(rule?.serialLength || 3, '0')
  return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
  try {
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { targetCode, targetName }
    })
    if (res?.data?.code === 200 && res?.data?.data) {
      return String(res.data.data)
    }
    throw new Error(res?.data?.message || '生成编号失败')
  } catch (err) {
    console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
    const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
      params: { targetCode, targetName }
    })
    const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
    if (list.length > 0) {
      return buildCodeFromRule(list[0])
    }
    throw new Error('未找到对应的编号规则，请先配置编号规则')
  }
}

const rules: FormRules = {
  warehouseName: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  warehouseCode: [{ required: true, message: '请填写仓库编号', trigger: 'blur' }]
}

onMounted(() => {
  const id = Number(route.query.warehouseId)
  if (!id) {
    ElMessage.error('缺少仓库编号')
    router.back()
    return
  }
  warehouseId.value = id
  loadWarehouseDetail(id)
  loadUsers()
  loadOrganizationTree()
})

const loadWarehouseDetail = async (id: number) => {
  try {
    const res = await myaxios.get(`/api/Warehouse/DetailWarehouse?warehouseid=${id}`)
    if (res.data?.code === 200 && res.data?.data) {
      const data = res.data.data
      ruleForm.warehouseCode = data.warehouseCode || ''
      ruleForm.warehouseName = data.warehouseName || ''
      ruleForm.warehouseCapacity = data.warehouseCapacity || ''
      ruleForm.userId = data.userId ? String(data.userId) : ''
      ruleForm.storagelocationNum = Number(data.storagelocationNum) || 0
      ruleForm.warehouseAddress = data.warehouseAddress || ''
      ruleForm.warehouseSort = data.warehouseSort ? String(data.warehouseSort) : ''
      ruleForm.warehouseLock = !!data.warehouseLock
      ruleForm.warehouseNote = data.warehouseNote || ''
      ruleForm.organizationId = data.organizationId ? String(data.organizationId) : ''
      ruleForm.warehousePhone = data.warehousePhone || ''
      ruleForm.warehouseState = data.warehouseState ? String(data.warehouseState) : '1'
      ruleForm.accountName = data.accountName || ''
      selectedOrganizationName.value = data.organizationName || ''
      loadStoragelocationList(id)
    } else {
      ElMessage.error('加载仓库信息失败')
    }
  } catch (error) {
    console.error('加载仓库详情失败:', error)
    ElMessage.error('加载仓库详情失败')
  }
}

const loadStoragelocationList = async (id: number) => {
  try {
    const res = await myaxios.get('/api/Warehouse/GetStoragelocation', {
      params: {
        warehouseId: id,
        pageindex: 1,
        pagesize: 9999
      }
    })
    if (res.data?.code === 200 && res.data?.data) {
      tableDatastoragelocation.value = (res.data.data.data || []).map((item: any) => ({
        ...item,
        saving: false
      }))
      ruleForm.storagelocationNum = tableDatastoragelocation.value.length
    }
  } catch (error) {
    console.error('加载库位列表失败:', error)
  }
}

const loadUsers = async () => {
  try {
    const res = await myaxios.get('/api/Warehouse/GetUser')
    userOptions.value = res.data?.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const loadOrganizationTree = async () => {
  try {
    const res = await myaxios.get('api/Organization/GetOrganizationTree', { params: { parentid: 0 } })
    const treeData = Array.isArray(res.data) ? res.data : []
    organizationTree.value = transformOrganizationTree(treeData)
  } catch (error) {
    console.error('获取组织树失败:', error)
  }
}

const transformOrganizationTree = (nodes: any[] = []): any[] => {
  return nodes.map(node => ({
    organizationId: node.organizationId ?? node.id,
    organizationName: node.organizationName ?? node.label ?? node.name ?? '',
    children: node.children ? transformOrganizationTree(node.children) : []
  }))
}

const openOrganizationDialog = () => {
  organizationDialogVisible.value = true
}

const handleOrganizationSelect = (data: any) => {
  const id = data.organizationId ?? data.id
  const name = data.organizationName ?? data.label ?? ''
  ruleForm.organizationId = id ? String(id) : ''
  selectedOrganizationName.value = name
  organizationDialogVisible.value = false
}

watch(organizationSearchText, val => {
  treeRef.value?.filter(val)
})

const filterNode: FilterNodeMethodFunction = (value: string, data: any) => {
  if (!value) return true
  const name = data.organizationName ?? data.label ?? ''
  return name.includes(value)
}

const buildWarehousePayload = () => {
  const raw = toRaw(ruleForm)
  const payload = {
    ...raw,
    warehouseId: warehouseId.value,
    storagelocationNum: tableDatastoragelocation.value.length
  }
  return JSON.parse(JSON.stringify(payload))
}

const saveWarehouse = async () => {
  if (!warehouseId.value) return
  saving.value = true
  try {
    const payload = buildWarehousePayload()
    const res = await myaxios.put(`/api/Warehouse/UpdateWarehouse?warehouseId=${warehouseId.value}`, payload)
    if (res.data?.code === 200) {
      ElMessage.success(res.data?.message || '保存成功')
      router.push('/GetWarehouse')
    } else {
      ElMessage.error(res.data?.message || '保存失败')
    }
  } catch (error: any) {
    console.error('保存仓库失败:', error)
    const msg = error?.response?.data?.message || error?.message || '保存仓库失败'
    ElMessage.error(msg)
  } finally {
    saving.value = false
  }
}

const saveStoragelocation = async (row: any) => {
  if (!row.storagelocationId) {
    ElMessage.warning('库位ID不存在')
    return
  }
  row.saving = true
  try {
    const res = await myaxios.put(`/api/Warehouse/UpdateStoragelocation?storagelocationId=${row.storagelocationId}`, {
      storagelocationId: row.storagelocationId,
      storagelocationCode: row.storagelocationCode || '',
      storagelocationName: row.storagelocationName || '',
      storagelocationCapacity: row.storagelocationCapacity || '',
      userId: Number(row.userId) || 0,
      storagelocationSort: Number(row.storagelocationSort) || 0,
      storagelocationState: Number(row.storagelocationState) || 1,
      storagelocationNote: row.storagelocationNote || '',
      warehouseId: warehouseId.value || 0
    })
    if (res.data?.code === 200) {
      ElMessage.success('保存库位成功')
      refreshStoragelocations()
    } else {
      ElMessage.error(res.data?.message || '保存库位失败')
    }
  } catch (error) {
    console.error('保存库位失败:', error)
    ElMessage.error('保存库位失败')
  } finally {
    row.saving = false
  }
}

const deleteStoragelocation = (row: any) => {
  if (!row.storagelocationId) return
  ElMessageBox.confirm('确认删除该库位吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await myaxios.put(`/api/Warehouse/AllDeleteStoragelocation?storagelocationIds=${row.storagelocationId}`)
        if (res.data?.code === 200) {
          ElMessage.success('删除成功')
          refreshStoragelocations()
        } else {
          ElMessage.error(res.data?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除库位失败:', error)
        ElMessage.error('删除库位失败')
      }
    })
    .catch(() => {})
}

const refreshStoragelocations = () => {
  if (warehouseId.value) {
    loadStoragelocationList(warehouseId.value)
  }
}

const openAddDrawer = () => {
  if (!warehouseId.value) {
    ElMessage.warning('仓库ID不存在')
    return
  }
  addDrawerVisible.value = true
}

const openImportDrawer = () => {
  ElMessage.warning('导入功能暂未实现')
}

const openUserDialog = () => {
  userSearchText.value = ''
  filteredUsers.value = userOptions.value
  userDialogVisible.value = true
}

watch(userSearchText, val => {
  if (!val) {
    filteredUsers.value = userOptions.value
  } else {
    const keyword = String(val).toLowerCase()
    filteredUsers.value = userOptions.value.filter((user: any) =>
      String(user.userName).toLowerCase().includes(keyword) ||
      String(user.userAccount || '').toLowerCase().includes(keyword)
    )
  }
})

const selectUser = (user: any) => {
  addStoragelocation.userId = String(user.userId)
  selectedAddUserName.value = user.userName
  userDialogVisible.value = false
}

const generateStoragelocationCode = async () => {
  generatingLocationCode.value = true
  try {
    addStoragelocation.storagelocationCode = await requestNumber('StorageLocation', '库位编号')
    ElMessage.success('编号生成成功')
  } catch (error: any) {
    console.error('生成库位编号失败:', error)
    ElMessage.error(error?.message || '生成库位编号失败')
  } finally {
    generatingLocationCode.value = false
  }
}

const resetAddStoragelocation = () => {
  addStoragelocation.storagelocationName = ''
  addStoragelocation.storagelocationCode = ''
  addStoragelocation.storagelocationCapacity = ''
  addStoragelocation.userId = ''
  addStoragelocation.storagelocationSort = 0
  addStoragelocation.storagelocationState = 1
  addStoragelocation.storagelocationNote = ''
  selectedAddUserName.value = ''
}

const createStoragelocation = async () => {
  if (!warehouseId.value) {
    ElMessage.error('仓库ID不存在')
    return
  }
  if (!addStoragelocation.storagelocationCode) {
    await generateStoragelocationCode()
    if (!addStoragelocation.storagelocationCode) {
      ElMessage.warning('请先生成库位编号')
      return
    }
  }
  addingStorage.value = true
  try {
    const res = await myaxios.post('/api/Warehouse/CreateStoragelocation', {
      ...addStoragelocation,
      warehouseId: warehouseId.value
    })
    if (res.data?.code === 200) {
      ElMessage.success('新增库位成功')
      addDrawerVisible.value = false
      resetAddStoragelocation()
      refreshStoragelocations()
    } else {
      ElMessage.error(res.data?.message || '新增库位失败')
    }
  } catch (error) {
    console.error('新增库位失败:', error)
    ElMessage.error('新增库位失败')
  } finally {
    addingStorage.value = false
  }
}
</script>

<style scoped>
.warehouse-update-page {
  padding: 16px;
}

.section-card {
  margin-bottom: 16px;
}

.section-title {
  font-size: 22px;
  font-weight: 600;
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 10px;
}

.pagination-info {
  color: #606266;
}

.footer-card {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 12px;
}

.drawer-content {
  padding-right: 16px;
}

.user-list-dialog {
  max-height: 320px;
  overflow-y: auto;
}

.user-item {
  padding: 10px 14px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.user-item:hover {
  border-color: #67c23a;
  background: #f0f9eb;
}

.user-name {
  font-weight: 600;
  color: #303133;
}

.user-account {
  font-size: 12px;
  color: #909399;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 12px 0;
}
</style>
